package com.example.sparkchaindemo;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.widget.NestedScrollView;

import com.example.sparkchaindemo.app.SparkHelper;
import com.hjq.permissions.OnPermission;
import com.hjq.permissions.XXPermissions;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 离线唤醒IVW70 e867a88f2
 * 调用流程：SDKinit-registerListener-start-write-end-engineUninit-SDKUninit
 * 注意:engineuninit仅当最终退出不使用唤醒的时候才调用，调用engineuninit后不能再重新start唤醒能力，否则引擎会报错崩溃
 */
public class IVWActivity extends AppCompatActivity {

    private final String TAG = "AEELog";
    private static final String ABILITYID = "e867a88f2";

    private AtomicBoolean isEnd = new AtomicBoolean(true);
    private AtomicBoolean isStartRecord = new AtomicBoolean(false);
    private EditText etKeyword;
    private TextView tv_notification, tv_db;

    private NestedScrollView mNesScroll;
    private TextView tvRecord, tvTime, startService, stopService;
    TextView tv_result, tv_statusInfo;
    Button btn_audio_start;
    private LinearLayout talkLayout;
    String asrFinalResult = "识别结果：\n";

    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if ("initAiKitSDK".equals(intent.getAction())) {
                int code = intent.getIntExtra("code", 1);
                if (code == 0) {
                    startService.setText("开启(运行中)");
                } else {
                    startService.setText("开启失败(" + code + ")");
                }
            }
            if ("startRecord".equals(intent.getAction())) {
                tv_result.setText("识别结果：\n");
                asrFinalResult = "识别结果：\n";

                tv_statusInfo.setText("录音中...");
                btn_audio_start.setText("录音中...");
                btn_audio_start.setEnabled(false);
            }
            if ("callSuccess".equals(intent.getAction())) {
                talkLayout.setVisibility(View.VISIBLE);
            }
            if ("rtasrCall".equals(intent.getAction())) {
                String content = intent.getStringExtra("content");
                tv_result.setText(content);
            }
            if ("rtasrCallFinished".equals(intent.getAction())) {
                btn_audio_start.setText("开始麦克风识别");
                btn_audio_start.setEnabled(true);
                talkLayout.setVisibility(View.GONE);
                tv_statusInfo.setText("录音结束");
            }
            if ("calculateVolume".equals(intent.getAction())) {
                int volume = intent.getIntExtra("volume", 0);
                tv_db.setText("当前分贝:" + volume);
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction("startRecord");
        myIntentFilter.addAction("callSuccess");
        myIntentFilter.addAction("rtasrCall");
        myIntentFilter.addAction("rtasrCallFinished");
        myIntentFilter.addAction("calculateVolume");
        registerReceiver(receiver, myIntentFilter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(receiver);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ivw);
        initView();
    }

    /**
     * 初始化控件
     */
    private void initView() {
        tv_notification = findViewById(R.id.ivw_tv_content);
        tv_db = findViewById(R.id.ivw_tv_db);
        mNesScroll = findViewById(R.id.ivw_nsv_scroll);
        etKeyword = findViewById(R.id.ivw_et_keyword);
        tvRecord = findViewById(R.id.tv_record);
        tvTime = findViewById(R.id.tv_time);
        startService = findViewById(R.id.startService);
        stopService = findViewById(R.id.stopService);
        talkLayout = findViewById(R.id.talkLayout);

        tv_result = findViewById(R.id.ai_rtasr_asrResult);
        tv_statusInfo = findViewById(R.id.ai_rtasr_testAudioPath);
        btn_audio_start = findViewById(R.id.ai_rtasr_audio_btn);
        tv_result.setMovementMethod(new ScrollingMovementMethod());

        etKeyword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (TextUtils.isEmpty(charSequence)) {
                    return;
                }
                SparkHelper.getInstance().setKeyword(charSequence.toString());
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        tvRecord.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SparkHelper.getInstance().getGlobalService().stopListen();
            }
        });
        startService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                requestPermission();
            }
        });
        stopService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //逆初始化
                startService.setText("开启");
                SparkHelper.getInstance().stopSparkService();
            }
        });
    }

    /**
     * 获取存储权限
     */
    private void requestPermission() {
        /**
         * 获取相关权限。
         * 本地存储的读写权限:用于SDK从workdir中读取资源文件或者测试音频，日志存放到workdir以及引擎运行结果的保存目录
         * 网络权限:首次运行鉴权时需要联网拉去协议，鉴权成功后，可在无网环境下运行，此时则可以不需要网络权限
         */
        XXPermissions.with(this).permission(
                "android.permission.WRITE_EXTERNAL_STORAGE"
                , "android.permission.READ_EXTERNAL_STORAGE"
                , "android.permission.INTERNET"
                , "android.permission.MANAGE_EXTERNAL_STORAGE"
                , "android.permission.RECORD_AUDIO"
                , "android.permission.READ_PHONE_STATE"
        ).request(new OnPermission() {
            @Override
            public void hasPermission(List<String> granted, boolean all) {
                Log.d(TAG, "SDK获取系统权限成功:" + all);
                for (int i = 0; i < granted.size(); i++) {
                    Log.d(TAG, "获取到的权限有：" + granted.get(i));
                }
                if (all) {
                    //启动service
                    SparkHelper.getInstance().startSparkService();
                }
            }

            @Override
            public void noPermission(List<String> denied, boolean quick) {
                if (quick) {
                    Log.e(TAG, "onDenied:被永久拒绝授权，请手动授予权限");
                    XXPermissions.startPermissionActivity(IVWActivity.this, denied);
                } else {
                    Log.e(TAG, "onDenied:权限获取失败");
                }
            }
        });
    }

//    private void initSDK() {
//        SparkUtils.initAiKitSDK(getApplication(), new CoreListener() {
//            @Override
//            public void onAuthStateChange(final ErrType type, final int code) {
//                Log.i(TAG, "core listener code:" + code);
//
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        switch (type) {
//                            case AUTH:
//                                authResult = code;
//                                if (code == 0) {
//                                    startService.setText("开启(运行中)");
//
//                                    //录音监听中
//                                    startListen();
//                                } else {
//                                    startService.setText("开启失败(" + authResult+")");
//                                }
//                                break;
//                            case HTTP:
//                                Toast.makeText(IVWActivity.this, "SDK状态：HTTP认证结果" + code,
//                                        Toast.LENGTH_SHORT).show();
//                                break;
//                            default:
//                                Toast.makeText(IVWActivity.this, "SDK状态：其他错误" + code,
//                                        Toast.LENGTH_SHORT).show();
//                        }
//                    }
//                });
//            }
//        });
//    }

    /**
     * 显示信息到界面
     */
    private void showInfo(final String info) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tv_notification.post(new Runnable() {
                    @Override
                    public void run() {
                        tv_notification.append("\r\n");
                        tv_notification.append(info);
                        mNesScroll.post(new Runnable() {
                            @Override
                            public void run() {
                                mNesScroll.fullScroll(View.FOCUS_DOWN);
                            }
                        });
                    }
                });
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


    private AtomicBoolean isStart = new AtomicBoolean(false);
    private final static int COUNT_TIME = 1024;

    public void startRecord() {
        tvRecord.post(new Runnable() {
            @Override
            public void run() {
                isStart.set(true);
                tvRecord.setText("停止监听");
                countDownTime();
            }
        });
    }

    public void stopRecord() {
        tvRecord.post(new Runnable() {
            @Override
            public void run() {
                isStart.set(false);
                tvRecord.setText("开始监听");

                if (timerTask != null) {
                    timerTask.cancel();
                }
                totalTime = 0;
                setTimeView();
            }
        });
    }

    private void countDownTime() {

        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (timerTask != null) {
            timerTask.cancel();
            timerTask = null;
        }
        timerTask = new TimerTask() {
            @Override
            public void run() {
                Message message = Message.obtain();
                message.what = COUNT_TIME;
                mHandle.sendMessage(message);
                totalTime++;
            }
        };
        timer = new Timer();
        timer.schedule(timerTask, 0, 1000);

    }

    private final Handler mHandle = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            if (msg.what == COUNT_TIME) {
                setTimeView();
            }
        }
    };
    private long totalTime = 0;
    private TimerTask timerTask;
    private Timer timer;

    private void setTimeView() {

        int second = (int) (totalTime % 60);
        int minuter = (int) ((totalTime / 60) % 60);
        int hour = (int) (totalTime / 3600);
        StringBuilder builder = new StringBuilder();
        if (hour < 10) {
            builder.append("0");
        }
        builder.append(hour).append(":");
        if (minuter < 10) {
            builder.append("0");
        }
        builder.append(minuter).append(":");
        if (second < 10) {
            builder.append("0");
        }
        builder.append(second);
        tvTime.setText(builder.toString());
    }

}